import React, {useState, useEffect} from 'react';
import {Modal, Form, Input, Select, Button, Spin, message} from 'antd';
import {getAcademyInfo} from "../../../api/academy.js";
import {getSpecialtyByAcademyId} from "../../../api/specialty.js";
import {getClassInfoBySpecialtyId} from "../../../api/classInfo.js";

const {Option} = Select;

const StudentFormModal = ({visible, onCancel, onOk, editingStudent}) => {
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [selectedAcademy, setSelectedAcademy] = useState('');
    const [selectedSpecialty, setSelectedSpecialty] = useState('');
    const [selectedClass, setSelectedClass] = useState('');
    const [gradeYear, setGradeYear] = useState('');

    const [academyList, setAcademyList] = useState([]);
    const [specialtyList, setSpecialtyList] = useState([]);
    const [classList, setClassList] = useState([]);
    const [years, setYears] = useState([]);
    const education = Form.useWatch('education', form);

    // 生成最近 N 年的选项
    useEffect(() => {
        const currentYear = new Date().getFullYear();
        const yearOptions = [];

        for (let i = currentYear; i >= 2000; i--) {
            yearOptions.push(i);
        }

        setYears(yearOptions);
    }, []);

    useEffect(() => {
        const fetchAcademyInfo = async () => {
            setLoading(true);
            try {
                const res = await getAcademyInfo(null);
                setAcademyList(res.data);
            } catch (error) {
                message.error('获取学院列表失败');
                console.error(error);
            } finally {
                setLoading(false);
            }
        };

        fetchAcademyInfo();
    }, []);

    // 根据 selectedAcademy 获取对应的专业
    useEffect(() => {
        if (!selectedAcademy) {
            setSpecialtyList([]);
            return;
        }

        const fetchSpecialtyList = async (academyId) => {
            if (!academyId) return;
            try {
                const res = await getSpecialtyByAcademyId(academyId);
                setSpecialtyList(res.data || []);
            } catch (error) {
                message.error('获取专业列表失败');
                console.error(error);
            }
        };

        fetchSpecialtyList(selectedAcademy);
    }, [selectedAcademy]);

    // 根据 selectedSpecialty 获取对应的班级
    useEffect(() => {
        if (!selectedSpecialty && !gradeYear) {
            setClassList([]);
            return;
        }

        const fetchClassesBySpecialty = async (specialtyId, gradeYear) => {
            if (!specialtyId && !gradeYear) return;
            try {
                const res = await getClassInfoBySpecialtyId(specialtyId, gradeYear);
                setClassList(res.data || []);
            } catch (error) {
                message.error('获取班级列表失败');
                console.error(error);
            }
        };

        fetchClassesBySpecialty(selectedSpecialty,gradeYear);
    }, [selectedSpecialty,gradeYear]);

    // 当 editingStudent 改变或 visible 为 true 时，更新表单和选中状态
    useEffect(() => {
        if (visible && editingStudent) {
            form.setFieldsValue({
                studentId: editingStudent.studentId,
                name: editingStudent.name,
                gender: editingStudent.gender === 1 ? '男' : '女',
                age: editingStudent.age,
                grade: editingStudent.grade,
                academyId: editingStudent.academyId,
                specialtyId: editingStudent.specialtyId,
                classId: editingStudent.classId,
                education: editingStudent.education,
            });

            setSelectedAcademy(editingStudent.academyId);
            setSelectedSpecialty(editingStudent.specialtyId);
            setSelectedClass(editingStudent.classId);
            setGradeYear(editingStudent.grade);
        } else {
            form.resetFields();
            setSelectedAcademy('');
            setSelectedSpecialty('');
            setSelectedClass('');
            setGradeYear('');
        }
    }, [editingStudent, form, visible]);

    // 处理入学年份选择
    const handleYearChange = (value) => {
        const year = String(value).slice(-2);
        setGradeYear(year);
    };

    // 生成学号
    useEffect(() => {
        if (!editingStudent) {
            generateStudentId();
        }
    }, [
        education,
        selectedAcademy,
        selectedSpecialty,
        selectedClass,
        gradeYear
    ]);

    const generateStudentId = () => {
        const educationMap = {
            '本科': '1',
            '研究生': '5'
        };
        const educationCode = education ? educationMap[education] || '' : '';
        const gradeCode = gradeYear || '';
        const academyCode = selectedAcademy ? academyList.find(a => a.id === selectedAcademy)?.academyCode || '' : '';
        const specialtyCode = selectedSpecialty ? specialtyList.find(s => s.id === selectedSpecialty)?.specialtyCode || '' : '';
        const classCode = selectedClass ? classList.find(c => c.classId === selectedClass)?.classCode || '' : '';
        // 获取序号
        const nextSeq = selectedClass
            ? (() => {
                const classInfo = classList.find(c => c.classId === selectedClass);
                const studentNum = classInfo?.studentNum ?? 0;
                const nextNumber = studentNum + 1;
                return nextNumber.toString().padStart(2, '0');
            })()
            : '01';

        const baseId = `${educationCode}${gradeCode}${academyCode}${specialtyCode}${classCode}`;

        const studentId = baseId + nextSeq;

        form.setFieldValue('studentId', studentId);
    };

    // 提交表单
    const handleOk = async () => {
        try {
            const values = await form.validateFields();
            setLoading(true);

            const submitData = {
                ...values,
                gender: values.gender === '男' ? 1 : 0,
                academyId: selectedAcademy,
                specialtyId: selectedSpecialty,
                classId: selectedClass
            };

            await onOk(submitData);
            setLoading(false);
        } catch (error) {
            console.error(error);
            setLoading(false);
        }
    };

    return (
        <Modal
            title={editingStudent ? '修改学生信息' : '新增学生'}
            open={visible}
            onOk={handleOk}
            onCancel={() => {
                form.resetFields();
                onCancel();
            }}
            footer={[
                <Button key="cancel" onClick={onCancel}>
                    取消
                </Button>,
                <Button key="submit" type="primary" loading={loading} onClick={handleOk}>
                    提交
                </Button>,
            ]}
        >
            <Spin spinning={loading}>
                <Form form={form} layout="vertical" name="student_form">
                    {/* 姓名 */}
                    <Form.Item
                        label="姓名"
                        name="name"
                        rules={[{required: true, message: '请输入学生姓名！'}]}
                    >
                        <Input placeholder="请输入姓名"/>
                    </Form.Item>

                    {/* 性别 */}
                    <Form.Item
                        label="性别"
                        name="gender"
                        rules={[{required: true, message: '请选择性别！'}]}
                    >
                        <Select placeholder="请选择性别">
                            <Option value="男">男</Option>
                            <Option value="女">女</Option>
                        </Select>
                    </Form.Item>

                    {/* 年龄 */}
                    <Form.Item
                        label="年龄"
                        name="age"
                        rules={[
                            {required: true, message: '请输入年龄！'},
                            {
                                pattern: /^\d+$/,
                                message: '请输入有效的数字年龄'
                            },
                            {
                                validator(_, value) {
                                    if (!value || (Number(value) >= 6 && Number(value) <= 100)) {
                                        return Promise.resolve();
                                    }
                                    return Promise.reject(new Error('年龄应在6~100岁之间'));
                                }
                            }
                        ]}
                    >
                        <Input placeholder="请输入年龄"/>
                    </Form.Item>

                    {/* 学历 */}
                    <Form.Item
                        label="学历"
                        name="education"
                        rules={[{required: true, message: '请选择学历！'}]}
                    >
                        <Select placeholder="请选择学历">
                            <Option key="本科" value="本科">本科</Option>
                        </Select>
                    </Form.Item>

                    {/* 入学年份 */}
                    <Form.Item
                        label="入学年份"
                        name="grade"
                        rules={[{required: true, message: '请选择入学年份！'}]}
                    >
                        <Select
                            showSearch
                            placeholder="请选择年份"
                            style={{width: '100%'}}
                            onChange={handleYearChange}
                            filterOption={(input, option) =>
                                option.children.toString().toLowerCase().includes(input.toLowerCase())
                            }
                        >
                            {years.map(year => (
                                <Option key={year} value={year}>
                                    {year}
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>

                    {/* 学院 */}
                    <Form.Item
                        label="学院"
                        name="academyId"
                        rules={[{required: true, message: '请选择学院！'}]}
                    >
                        <Select
                            placeholder="请选择学院"
                            onChange={(value) => {
                                setSelectedAcademy(value);
                                form.setFieldValue('specialtyId', null); // 清空专业
                                form.setFieldValue('classId', null);     // 清空班级
                            }}
                        >
                            {academyList.map(academy => (
                                <Option key={academy.id} value={academy.id}>
                                    {academy.academyName}
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>

                    {/* 专业 */}
                    <Form.Item
                        label="专业"
                        name="specialtyId"
                        rules={[{required: true, message: '请选择专业！'}]}
                    >
                        <Select
                            placeholder="请先选择学院"
                            disabled={!selectedAcademy}
                            onChange={(value) => {
                                setSelectedSpecialty(value);
                                form.setFieldValue('classId', null); // 清空班级
                            }}
                        >
                            {specialtyList.map(specialty => (
                                <Option key={specialty.id} value={specialty.id}>
                                    {specialty.specialtyName}
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>

                    {/* 班级 */}
                    <Form.Item
                        label="班级"
                        name="classId"
                        rules={[{required: true, message: '请选择班级！'}]}
                    >
                        <Select
                            placeholder="请先选择专业和年份"
                            disabled={!selectedSpecialty || !gradeYear}
                            onChange={(value) => {
                                setSelectedClass(value);
                            }}
                        >
                            {classList.map(cls => (
                                <Option key={cls.classId} value={cls.classId}>
                                    {cls.className}
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>

                    {/* 学号 */}
                    <Form.Item
                        label="学号"
                        name="studentId"
                        rules={[{required: true, message: '学号不能为空！'}]}
                    >
                        <Input
                            placeholder="自动生成"
                            disabled={!!editingStudent}
                            readOnly
                        />
                    </Form.Item>
                </Form>
            </Spin>
        </Modal>
    );
};

export default StudentFormModal;